package com.testfileupload.uploadimg.design.memorandum.more;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils {
    public static Map<String, Object> backupProp(Object bean) {
        Map<String, Object> result = new HashMap<>();
        try {
            //获得bean的描述
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            //获取属性描述
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            //遍历所有属性
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                //属性名称
                String name = propertyDescriptor.getName();
                //属性的方法
                Method readMethod = propertyDescriptor.getReadMethod();
                //读属性的值
                Object invoke = readMethod.invoke(bean, new Object[]{});
                if (!name.equalsIgnoreCase("class")) {
                    result.put(name, invoke);
                }
            }

        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void restoreProp(Object bean, Map<String, Object> stateMap) {
        //获得bean的描述
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(bean.getClass());
            //获取属性描述
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            //遍历所有属性
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                //属性名称
                String name = propertyDescriptor.getName();
                if (stateMap.containsKey(name)){
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(bean,new Object[]{stateMap.get(name)});
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
